package io.github.lee.repository.jel.repo

import androidx.core.net.toUri
import io.github.lee.core.repository.BaseRepository
import io.github.lee.core.repository.data.Response
import io.github.lee.repository.jel.api.ApiModule
import io.github.lee.repository.jel.api.UserApi
import io.github.lee.repository.jel.dao.SessionDao
import io.github.lee.repository.jel.data.Page
import io.github.lee.repository.jel.data.Session
import io.github.lee.repository.jel.domain.Item
import io.github.lee.repository.jel.domain.LoginResponse
import javax.inject.Inject

private const val PATH_LOGIN = "Users/AuthenticateByName"

class UserRepository @Inject constructor(
    private val dao: SessionDao
) : BaseRepository() {
    private val api: UserApi by lazy {
        ApiModule.userApi
    }

    suspend fun login(
        sessionName: String, host: String,
        username: String, password: String,
    ): Response<LoginResponse> {
        val url = host.toUri().buildUpon()
            .appendEncodedPath(PATH_LOGIN)
            .build().toString()

        val map = mapOf(
            "Username" to username,
            "Pw" to password
        )
        val result = api.login(url, map)
        //本地缓存
        val token = result.data?.accessToken
        val userId = result.data?.user?.id
        val session = Session(sessionName, host, username, password, userId, token)
        dao.insertAbort(session)
        return result
    }


    suspend fun views(userId: String?): Response<Page<Item>> =
        api.views(userId ?: "")

}